package com.weichai.app.page.home.viewmodel;

import android.text.TextUtils;

import androidx.lifecycle.MediatorLiveData;
import androidx.lifecycle.MutableLiveData;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.weichai.app.arch.base.BaseViewModel;
import com.weichai.app.arch.config.CacheConstant;
import com.weichai.app.arch.utils.MMKVUtil;
import com.weichai.app.bean.EntranceEntity;
import com.weichai.app.page.main.MainModel;

import java.util.List;

public class EditApplicationVM extends BaseViewModel {
    public MutableLiveData<List<EntranceEntity>> entranceList = new MediatorLiveData<>();
    public MutableLiveData<List<EntranceEntity>> entranceServiceList = new MediatorLiveData<>();
    public MutableLiveData<Boolean> isEdit = new MediatorLiveData<>();
    private Gson gson;

    public void getEntranceList() {
        gson = new Gson();
        String entranceListJson = MMKVUtil.getString(CacheConstant.KEY_ENTRANCE_HOME);
        String entranceServiceListJson = MMKVUtil.getString(CacheConstant.KEY_ENTRANCE_SERVICE);
        // 首页应用
        if (!TextUtils.isEmpty(entranceListJson)) {
            List<EntranceEntity> list = gson.fromJson(entranceListJson, new TypeToken<List<EntranceEntity>>() {
            }.getType());
            entranceList.setValue(list);
        }

        // 服务
        if (!TextUtils.isEmpty(entranceServiceListJson)) {
            List<EntranceEntity> list = gson.fromJson(entranceServiceListJson, new TypeToken<List<EntranceEntity>>() {
            }.getType());
            entranceServiceList.setValue(list);
        }
    }

    public void save() {
        isEdit.setValue(false);
        MMKVUtil.save(CacheConstant.KEY_ENTRANCE_HOME, gson.toJson(entranceList.getValue()));
        MMKVUtil.save(CacheConstant.KEY_ENTRANCE_SERVICE, gson.toJson(entranceServiceList.getValue()));
        getViewModelOfApp(MainModel.class).entranceList.setValue(entranceList.getValue());
    }
}
